<template>
  <view>
    <text class="username-text" v-if="disabled">{{ userName }}</text>
    <uni-data-select
      v-else
      v-model="props.userId"
      :localdata="userOptions"
      @change="handleChange"
    ></uni-data-select>
  </view>
</template>

<script setup lang="ts">
import {usePmUserApi} from "@/api/pm/user";

defineOptions({ name: 'PmUserSelect' })

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  userId: {
    type: [String, Number, Array<string | number>],
    default: null,
  },
  showDept: {
    type: Boolean,
    default: true,
  }
})

const userName = computed(() => {
  const list = toRaw(allUserList.value);
  if (!props.userId || !list || !list.length) {
    return '暂无';
  } else {
    const userList = Array.isArray(props.userId) ? props.userId : [props.userId]
    const resUser = list.filter((u: UserForm) => userList.includes(u.id));
    if (resUser) {
      const resUserName = resUser.map(user => {
        return props.showDept ? `${user.deptName}-${user.nickname}` : user.nickname
      })
      return resUserName.join(',');
    }
    return `未知（${props.userId}）`;
  }
})


type UserOption = {
  value: string | number,
  text: string,
  deptName: string,
}
const userOptions = ref<UserOption[]>([]);

function getUserOptions() {
  const list = toRaw(allUserList.value);
  if (list && list.length) {
    userOptions.value = list.map((u: UserForm) => {
      return {
        value: u.id,
        text: props.showDept ? `${u.deptName}-${u.nickname}` : u.nickname,
        deptName: u.deptName,
      };
    });
  } else {
    userOptions.value = [];
  }
}

const $emit = defineEmits(['update:userId']);
function handleChange(val: string) {
  $emit('update:userId', val);
}

const allUserList = ref<UserForm[]>([]);
function getAllUserList() {
  usePmUserApi().listSimpleUsers().then((res) => {
    if (res.code === 0 && res.data) {
      allUserList.value = res.data;
      getUserOptions();
    }
  })
}

onLoad(() => {
  getAllUserList();
})
</script>

<style scoped lang="scss">
.username-text {
  text-transform: none;
}

:deep(.uni-select) {
  height: 80rpx !important;
}
</style>
